package ru.st.selenium.pages;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.PageFactory;

import java.util.List;

/*
 * Sample page
 * 
 * @author Sebastiano Armeli-Battana
 */
public class HomePage extends Page {

	private final String H1_TAG = "h1";
	
	@FindBy(how = How.TAG_NAME, using = H1_TAG)
	@CacheLookup
	private WebElement h1Element;

    @FindBy(xpath = "//a[@href='./?go=add']")
    private WebElement addMovieBtn;

    @FindBy(xpath = "//input[@id='q']")
    private WebElement searchInput;

    @FindBy(xpath = "//div[@id='results']/a/div")
    private List<WebElement> results;

    @FindBy(xpath = "//div[@id='results']")
    private WebElement result;

    public WebElement getResult() {
        return result;
    }

    public HomePage(WebDriver webDriver) {
		super(webDriver);
	}
	
	public String getH1() {
		return h1Element.getText();
	}

    public HomePage searchForMovie(String movie) {
        searchInput.clear();
        searchInput.sendKeys(movie, Keys.RETURN);
//        searchInput.sendKeys(Keys.ENTER);
        return this;
    }

    public List<WebElement> getListOfAllFoundMovies() {
        return results;
    }

    public NewMoviePage navigateToNewMoviePage() {
        addMovieBtn.click();
        return PageFactory.initElements(getWebDriver(), NewMoviePage.class);
    }

    public SimpleMoviePage findMovieAndOpen(String title) {
        WebElement movie = getWebDriver().findElement(By.xpath("//*[contains(text(), '"+title+"')]"));
        movie.click();
        return PageFactory.initElements(getWebDriver(), SimpleMoviePage.class);
    }

}
